// env
const isProdMode = Object.is(process.env.NODE_ENV, 'production')

const express = require('express')
const app = express()
const { Nuxt, Builder } = require('nuxt')

const host = !isProdMode ? '0.0.0.0' : (process.env.HOST || '127.0.0.1')
const port = process.env.PORT || 9002

app.set('port', port)

// Import and Set Nuxt.js options
const config = require('./nuxt.config')
config.dev = !isProdMode

const nuxt = new Nuxt(config)
app.use(nuxt.render)

// Build only in dev mode
if (config.dev) {
	const builder = new Builder(nuxt)
  builder.build().catch((error) => {
  	// eslint-disable-line no-console
    console.error(error)
    process.exit(1)
  })
}

const server = require('http').Server(app)
server.listen(port, host)

console.log(`Nuxt.js SSR Server ${host}:${port}, at ${new Date().toLocaleString()}, env: ${process.env.NODE_ENV}`)
